define([
  'text!./live_table_widget.html',
  '../../service',
  "../../utils/i18n",
  "pager"
  ], function (sourceHTML,api, i18n) {

  	var widget = avalon.ui.livetablewidget = function(element, data, vmodels){
  	

	    var vmodel = avalon.define(data.livetablewidgetId, function(vm){
	    	vm.results = {};
	    	vm.collections = [];
	    	vm.noCategory = false;
		    vm.params = {
		            method: null,
		            query:{
		               
		            }
		        };
		    // @TODO search Key word.
			vm.pager = {
		          currentPage: vm.currentPage || 1,
		          perPages: vm.perPages ||  8,
		          showJumper: false,
		          alwaysShowNext: true, //@config {Boolean} 总是显示向后按钮
		          alwaysShowPrev: true,
		          pageCount:1
		          
		    }; 

			_.merge(vm, data.livetablewidgetOptions);

			vm.pager.onJump = function(e, data) {
	              // if backend handle pages
	              //location.href = "#page=" + data.currentPage
	              vm.params.query.PageIndex = data.currentPage;
	              vm._getAndRenderCollections(vm.params, function(res){
	              	vm.pager.currentPage = data.currentPage;
	              });
	              
	          }

	  		vm.currentOrder = vm.orders[0];
	  		vm.currentStyle = vm.toggleBtns[1].style;
	  	
	  		vm.gridStyle = function(){
	  			return  currentStyle == vm.toggleBtns[0];
	  		}

			vm.$skipArray = ["orders","currentOrder","toggleBtns",
			"results","pager","params"];


			vm.changeOrders = function(e,order, elem){
				vm.currentOrder = order; 
				avalon.mix(vm.params, {query:order.query})

	  			vm.$fire("searching", vm.params);
	  		};

	  		vm.changeStyle = function(s){
				if(vm.currentStyle != s.style){
					vm.toggleStyle = !vm.toggleStyle;
					vm.currentStyle = s.style;	
				}; 
	  		};

	  		vm.changeCategory = function(c){
	  			if(!_.has(vm.params.query,"queryString")){
	  				vm.params.query.queryString = [];
	  			}
	  			var qs = vm.params.query.queryString;
	  			// console.log(vm.params);
	  			_.uniq(qs.push(c.key+"="+c.guid));

	  			vm.$fire("searching", vm.params);

	  		};


	  		vm._getAndRenderCollections = function(query,cb){
	  			return api.getItems(avalon.mix(vmodel.params, {PageIndex:vmodel.pager.currentPage}),function(res){
		            
	  				if(res && res.list){
	  					vm.results = res;
	  					vm.collections.clear();
			            vm.collections = vm.results.list;
		                
			            //stub
			            if(vm.collections.length > vm.perPages){
			            	vm.collections = vm.collections.slice(0,vm.perPages);
			            }

			            _.each(vm.collections, function(el){
			            	var n = el.CommentCount || 0;
			            	el.collectionsCount = i18n.ngettext("collections %s person","collections %s people",n);

			            })

		                vm.pager.totalItems = vm.results.query.recordCount;
		                vm.pager.currentPage = vm.results.query.pageIndex;
                    	vm.pager.perPages = vm.results.query.pageSize;
                    	vm.pager.pageCount = vm.results.query.pageCount;
	  				}else{
	  					vm.pager.totalItems = 0;
	  				}
	  				
	  				element.innerHTML = sourceHTML;
	                avalon.scan(element, [vmodel].concat(vmodels));
	  				
	                if(cb){
	                	cb(res);
	                }
		  			 setTimeout(function(){
                        $(window).trigger("imagesDefault");
                    },100)
	            }) 
	  		}
	  		vm._getAndRenderCollectinosState = function(query,cb){
	  			

	  			if(vm.collections.length <= 0) return;
	  			return api.getItems(query,function(res){
	  				for(var i = 0 ; i < vm.collections.length ;i ++){
	  					var re = res.data[vm.collections[i].id];

	  					if(re){
	  						if(re.title){
	  							vm.collections[i].liveTitle = re.title;
	  						}
	  						if(re.startTimeTip){
	  							vm.collections[i].liveStartTimeTip = re.startTimeTip;
	  						}
	  						if(re.speaker)
	  							vm.collections[i].liveSpeaker = re.speaker;

	  						vm.collections[i].isLive = (re.RecordEquipmentCode==2||re.RecordEquipmentCode == 3)?true:false;

	  					}
	  				}
	  				if(cb){
	                	cb(res);
	                }
	                
	                $(".online-img").each(function(i,_self){
	                	if(_self.original != 2) return;

	                	var $self = $(_self);
                		$("<img>").one("load",function(){
                			var original2 = $self.attr("data-original2");
                			$self.attr("src",original2+"?_="+(new Date() - 0));
                		}).one("error",function(e){
                        	$(e.target).unbind("load");
                		}).attr("src",$self.attr("data-original2"))
	                })
	                
	  			})
	  		} 
	  			


	  		vm.$init = function(){
	  			// @TODO cached but not once whole page.
	  			
	            return vm._getAndRenderCollections(vm.params,function(){
	            	element.innerHTML = sourceHTML;
	                avalon.scan(element, [vmodel].concat(vmodels));
	                vm.$fire("refresh");
	            });

	            
	  		}
	  		vm.$remove = function(){
				element.innerHtml = element.textContent = "";
  	
	  		}
	  	});

	    vmodel.$watch("refresh",function(){
			var query = "";
			for(var i = 0; i < vmodel.collections.length;i++){
				query += "&id="+vmodel.collections[i].id;
			}		    	
	    	var params = {
		            method: api.getOnlinesState,
		            query:query
		        }
	    	return vmodel._getAndRenderCollectinosState(params,function(){
	    		// element.innerHTML = sourceHTML;
	      //       avalon.scan(element, [vmodel].concat(vmodels));
	    	})
	    })

  		vmodel.$watch("searching", function(query){
			vmodel._getAndRenderCollections(query);
		})
		vmodel.$watch("searchKeyWord", function(searchKeyWord){
			vmodel.params.query.SearchKey = searchKeyWord;
			vmodel._getAndRenderCollections(vmodel.params)

		})



	    vmodel.$watch("perPages", function(a) {
          var widget = avalon.vmodels.pp
          if (widget) {
              widget.perPages = a
          }
	    })

	  	return vmodel;
	  };
	widget.defaults = {
		searchLang: {
			all: i18n.gettext("all results"),
			noresult : i18n.gettext("no results")
		},

		toggleStyle: false,

	    toggleBtns: [{
	   		title: "table display",
			style: "grid-toggle-btn"
	   		
	    },{
	   		title: "grid  display",
	   		style: "list-toggle-btn"
	   	}],
	    orders:[{
		    title:"推荐排行",
		    target:"recommendedPanel",
		    query: {
		      order: "order by recommended"
		    },
		    results:[]
	    },{
	      title:"最新发布",
	      target:"lastestPanel",
	       query: {
		      order: "order by latest"
		    },
	      results:[]
	    },{
	      title:"热度排行",
	      target:"hotsPanel",
	      query: {
		      order: "order by recommended"
		    },
	      results:[]
	    },{
	      title:"关注排行",
	      target:"attentionPanel",
	      query: {
		      order: "order by recommended"
		    },
	      results:[]
	    }]
	  }
	return avalon;

});